var os = require('os');
var fs = require('fs');
var ak = require('./waapi.js').ak;
var autobahn = require('autobahn');
var sounddata = require('./sounddata');
var eventdata = require('./eventdata');
var xlsxhandler = require('./xlsxhandler');
var wavinfo = require('./wavinfo');

var eventindex = 1;

var wavi = 0;
var wavj = 0;

var dataarray = [];
var eventarray = [];

var projectname = '';
// Create the WAMP connection
var connection = new autobahn.Connection({
        url: 'ws://localhost:8084/waapi',
        realm: 'realm1',
        protocols: ['wamp.2.json']
    });

// Setup handler for connection opened
connection.onopen = function (session) {

    // Call getInfo
    var query = {
        from:
            {path: ['\\Actor-Mixer Hierarchy']},
        transform:[
            {select:['descendants']},
        ]
    };
    
    var options = {
        //return: ['id', 'name', 'type', 'parent', '@ActionType', '@Target']
        return: ['id', 'name', 'type', 'parent', 'sound:originalWavFilePath', '@IsLoopingEnabled', '@PositioningType', '@Volume', '@Pitch', '@OutputBus']
    };
    
    session.call('ak.wwise.core.object.get', [], query, options).then(
        function (res) {
            // Print the name
            var objects = res.kwargs.return;
            for(let i = 0; i < objects.length;++i ){
                if (objects[i].type == 'Sound'){
                    data = new sounddata(objects[i].id, objects[i].name, objects[i].parent.id, objects[i].parent.name, objects[i]['@IsLoopingEnabled'], objects[i]['@PositioningType'], objects[i]['@Volume'], objects[i]['@Pitch'], objects[i]['@OutputBus'].name, objects[i]['sound:originalWavFilePath']);
                    dataarray.push(data);
                    //console.log(`${objects[i].name}` + `,${objects[i].type}` + `,${objects[i]['@IsLoopingEnabled']}` + `,${objects[i]['@PositioningType']}` + `,${objects[i].parent.name}`);
                }
            }
            querymusic(session);
        },
        function (error) {
            console.log(`error: ${error}`);
        }
    )
}

querymusic = function(session){
    var query = {
        from:
            {path: ['\\Interactive Music Hierarchy']},
        transform:[
            {select:['descendants']},
        ]
    };
    
    var options = {
        return: ['id', 'name', 'type', 'parent', 'sound:originalWavFilePath', '@IsLoopingEnabled', '@PositioningType', '@Volume', '@Pitch', '@OutputBus']
    };
    
    session.call('ak.wwise.core.object.get', [], query, options).then(
        function (res) {
            // Print the name
            var objects = res.kwargs.return;
            for(let i = 0; i < objects.length;++i ){
                if (objects[i].type == 'MusicTrack'){
                    data = new sounddata(objects[i].id, objects[i].name, objects[i].parent.id, objects[i].parent.name, objects[i]['@IsLoopingEnabled'], objects[i]['@PositioningType'], objects[i]['@Volume'], 0, objects[i]['@OutputBus'].name, objects[i]['sound:originalWavFilePath']);
                    dataarray.push(data);
                    //console.log(`${objects[i].name}` + `,${objects[i].type}` + `,${objects[i]['@IsLoopingEnabled']}` + `,${objects[i]['@PositioningType']}` + `,${objects[i].parent.name}`);
                }
            }
            queryevent(session)
        },
        function (error) {
            console.log(`error: ${error}`);
        }
    )
}

queryevent = function(session){
    var query = {
        from:{path: ['\\Events']},
        transform:[
            {select:['descendants']},
        ]
    };

    var options = {
        return: ['id', 'name', 'type', 'parent', '@ActionType', '@Target']
    };

    session.call('ak.wwise.core.object.get', [], query, options).then(
        function (res) {
            var events = res.kwargs.return;
            for(let i = 0; i < events.length;++i ){
                if (events[i].type == 'Event'){
                    event = new eventdata(eventindex,events[i].id, events[i].name);
                    eventindex++;
                    eventarray.push(event);
                    console.log(`${events[i].name}`)
                }
                else if (events[i].type == 'Action'){
                    addaction(events[i].id,events[i].parent.id,events[i].parent.name,events[i]['@ActionType'],events[i]['@Target'].id,events[i]['@Target'].name);
                }
            }
            parseEvent(session,0);
        },
    )
};

parseEvent = function(session,index){
    addSoundToEvent(dataarray[index],dataarray[index].id);
    var query = {
        from: {id: [dataarray[index].id]},
        transform:[
            {select:['ancestors']},
        ]
    };

    var options = {
        return: ['id','name','type']
    };

    try{
        session.call('ak.wwise.core.object.get', [], query, options).then(
            function (res) {
                var targets = res.kwargs.return;
                for(let i = 0; i < targets.length;++i ){
                    if (targets[i].type.indexOf('Container') > 0)
                        addSoundToEvent(dataarray[index],targets[i].id,targets[i].type);
                }
                console.log(`${index}` + `,${targets.length}` + `,${dataarray.length}`);
                index++;
                if (index < dataarray.length){
                    parseEvent(session,index);
                }
                else{
                    printdata(session);
                }
            },
        )
    }catch(e){
        console.log(`${index}` + `,` + `,${dataarray.length}` + `,${e}`);
        index++;
        if (index < dataarray.length){
            parseEvent(session,index);
        }
        else{
            printdata(session);
        }
    }
}

addSoundToEvent = function(sound,id,type){
    eventarray.forEach(function(event,index){
        if (event.tid == id){
            sound.setContainer(type);
            event.addSound(sound);
        }
    })
}

sorttarget = function(tempdata,data,index){
    var arr = []
    tempdata.forEach(function(e,j){
        var num = 0;
        var found = false;
        for (let x = 0; x < arr.length; x++){
            if (arr[x].length > 0){
                if (e[index] == arr[x][0][2]){
                    arr[x].push(e);
                    found = true;
                    break;
                }
            }
        }
        if (!found){
            var arr1 = []
            arr1.push(e);
            arr.push(arr1);
        }
    })
    arr.forEach(function(ad,m){
        ad.forEach(function(ade,n){
            data.push(ade);
        })
    })
    tempdata.length = 0;
}

sortby = function(dt,index){
    var id = dt[0][0];
    var tempdata = [];
    var data = []
    for (let i = 0; i < dt.length; i++){
        if (id == dt[i][0]){
            
        }
        else {
            if (tempdata.length > 0){
                sorttarget(tempdata,data,index);
            }
            id = dt[i][0];
        }
        tempdata.push(dt[i]);
    }
    if (tempdata.length > 0){
        sorttarget(tempdata,data,index)
        tempdata.length = 0;
    }
    return data;
}

writefile = function(dt){
    var data = [];
    dt.forEach(function(e,index){
        var element = [e[0],e[1],e[2],e[3],e[5],e[6],e[7],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15]]
        data.push(element);
    })
    data.sort(function(a,b){
        return a[0]-b[0];
    })
    data = sortby(data,2);
    var xh = new xlsxhandler();
    xh.WriteFile(projectname,data);
    //process.exit();
}

addaction = function(id,pid,pname,actiontype,tid,tname){
    var found = false;
    var eid = eventindex;
    eventarray.forEach(function(event,index){
        if (event.id == pid){
            if (event.aid == ''){
                event.addAction(id,actiontype,tid,tname);
                found = true;
                return;
            }
            else{
                eid = event.index;
            }
        }
    });

    if (!found){
        event = new eventdata(eid,pid,pname);
        event.addAction(id,actiontype,tid,tname);
        eventarray.push(event);
    }
}

getprojectname = function(dir){
    var file = dir;
    if (os.platform() == 'darwin'){
        var tmp = os.homedir() + dir.split(':')[1];
        file = tmp.split('\\').join('/');
    }
    fs.readdir(file,function(err,files){
        if (files){
            files.forEach(function(file, index){
                var strs = file.split('.wproj')
                if (strs.length > 1 && strs[1] == ''){
                    projectname = strs[0];
                    return;
                }
            })
        }
    })
}

parsecontainer = function(dt,session){
    var count = 0;
    dt.forEach(function(data,index){
        if (data[5] == 'RandomSequenceContainer'){
            var query = {
                from: {id: [data[4]]},
                transform:[]
            };
        
            var options = {
                return: ['@RandomOrSequence']
            };

            count++;

            try{
                session.call('ak.wwise.core.object.get', [], query, options).then(
                    function (res) {
                        var targets = res.kwargs.return;
                        if (targets.length > 0){
                            if (targets[0]['@RandomOrSequence'] == 0){
                                data[5] = 'SequenceContainer'
                            }
                            else if (targets[0]['@RandomOrSequence'] == 1){
                                data[5] = 'RandomContainer'
                            }
                        }
                        count--;
                        if (count == 0){
                            connection.close();
                            writefile(dt);
                        }
                    }
                )
            }
            catch(e){

            }
        }
    })
    if (count == 0){
        connection.close();
        writefile(dt);
    }
}

printdata = function(session){
    var dt = [];
    console.log("begin printdata")
    var wi = new wavinfo();
    var title = ['ID','Event','Target','ActionType','cid','Container','AssetName','Loop','Position','Volume','Pitch','OutputBus','AudioFile','NumofChannel','Duration','SampleRate'];
    dt.push(title);
    var beEnd = false;
    eventarray.forEach(function(data,index){
        if (data.sounds.length > 0){
            data.sounds.forEach(function(sound,idx){
                console.log(`${data.id}` + `,${data.name}` + `,${data.aid}` + `,${data.tid}` + `${data.tname}` + `,${data.actiontype}` + `,${sound.container}` + `,${sound.name}` + `,${sound.loop}` + `,${sound.position}` + `,${sound.volume}` + `,${sound.pitch}` + `,${sound.outputbus}` + `,${sound.audiofile}`);
                var st = [data.index,data.name,data.tname,data.actiontype,data.tid,sound.container,sound.name,sound.loop,sound.position,sound.volume,sound.pitch,sound.outputbus,sound.audiofile];
                if (sound.audiofile && sound.audiofile != ''){
                    var strarr = sound.audiofile.split('\Originals');
                    if (strarr.length > 1){
                        st[12] = 'Originals' + strarr[1];
                        if (projectname == ''){
                            projectname = '.xlsx';
                            getprojectname(strarr[0]);
                        }
                    }
                }
                wavi++;
                wi.getWavInfo(sound.audiofile,function(err,xx){
                    if (xx){
                        xx.forEach(function(ww,index){
                            st.push(ww);
                        })
                    }
                    dt.push(st);
                    wavj++;
                    if (beEnd && wavj == wavi){
                        parsecontainer(dt,session);
                    }
                })
            })
        }
        else
        {
            console.log(`${data.id}` + `,${data.name}` + `,${data.aid}` + `,${data.tid}` + `,${data.actiontype}` + `,${data.volume}` + `,${data.pitch}` + `,${data.outputbus}` + `,` + `,` + `,` + `,` + `,`);
            var st = [data.index,data.name,data.tname,data.actiontype,data.volume,data.pitch,data.outputbus,'','','','','','','',''];
            dt.push(st);
        }
    });
    beEnd = true;
    if (wavi==0){
        parsecontainer(dt,session);
    }
};

connection.onclose = function (reason, details) {
    if (reason !== 'lost') {
        console.log("Connection closed. Reason: " + reason);
    }
    //printdata();
//    process.exit();
};

// Open the connection
var ExportProject = function(){
    connection.open();
}

exports.ExportProject = ExportProject;
